﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace UDPSocketProject
{
    public class UDPSocketServices
    {
        public Socket socketListen
        {
            get;
            set;
        }

        public IPEndPoint ipEndPoint
        {
            get;
            set;
        }

        public UDPSocketServices()
        {
        }

        public UDPSocketServices(IPAddress ipaddress, int port)
        {
            this.ipEndPoint = new IPEndPoint(ipaddress, port);
            this.socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }

        public void StartListen()
        {
            this.socketListen.Bind(this.ipEndPoint);
            Console.WriteLine("服务器已启动，开始监听客户端连接，接收数据");
            try
            {
                while (true)
                {
                    string result = string.Empty;
                    if (this.socketListen.Available < 1)
                    {
                        Thread.Sleep(20);
                    }
                    else
                    {
                        byte[] data = new byte[1366];
                        int NumBytes = this.socketListen.Receive(data);
                        Console.WriteLine(Environment.NewLine);
                        if (NumBytes > 0)
                        {
                            ReceiveHandler.ReceiveDataHandler(data, NumBytes);
                            //RouterDataManager routerDataManager = new RouterDataManager(data, NumBytes);
                            //ThreadStart childref = new ThreadStart(routerDataManager.SaveDataFrame);
                            //Thread childThread = new Thread(childref);
                            //childThread.Start();
                        }
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("++++++++++++++++++服务器出现异常++++++++++++++++++++++++++++");
                string a = e.ErrorCode.ToString();
                Console.WriteLine(e.Message + e.ErrorCode);
            }
        }
    }
}
